package com.licode.codekit.buildprj;

import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.licode.codekit.db.EntityBuilder;
import com.licode.codekit.db.GenerateCtx;
import com.licode.codekit.db.Table;
import com.licode.codekit.utils.FileUtil;
import com.licode.codekit.utils.StrUtil;
import org.jsoup.internal.StringUtil;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 * @author licode
 */
public class EntityGenerateBuilder {
    private final String rootPath;
    private final String author;

    public EntityGenerateBuilder(String rootPath, String author) {
        this.rootPath = rootPath;
        this.author = author;
    }

    private String getRootDir(String dir) {
        String zipRoot = dir;
        if (dir != null && dir.length() >= 2) {
            if (!dir.endsWith("/")) {
                zipRoot = dir + "/";
            }

            return zipRoot;
        } else {
            return "";
        }
    }

    public boolean buildEntityClass(Project rootPrj, java.util.List<Table> tabs, int tablePrefix) {
        boolean buildFlag = true;
        String rootDir = this.getRootDir(rootPath) + "/";
        File file = new File(rootDir);

        if (!(file.exists() && file.isDirectory())) {
            Messages.showMessageDialog(rootPrj, "目录不存在！",
                    "温馨提示", Messages.getInformationIcon());
            return false;
        }

        for (Table table : tabs) {
            try {
                EntityBuilder builder = new EntityBuilder();
                GenerateCtx gCtx = new GenerateCtx(rootDir, "Entity");
                gCtx.setAuthor(this.author);
                gCtx.setEntityMode(true);
                gCtx.setTablePrefix(tablePrefix);
                builder.generate(table, gCtx);
            } catch (Exception e) {
                buildFlag = false;
                break;
            }
        }

        if (!buildFlag) {
            Messages.showMessageDialog(rootPrj, "实体创建失败！",
                    "温馨提示", Messages.getInformationIcon());
        }

        return buildFlag;
    }

}
